<?php

/**
 * Impress - Open source digital signage
 *
 * @link http://digitalsignage.tk
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Impress
 * @package Impress
 */

/**
 * This class dispatches the request to the right controller.
 *
 * @package Impress
 * @subpackage Dispatchers
 */

abstract class ADS_DefaultDispatcher{
    
    /**
     * Method loads correct controller according to requested module 
     * and executes action on controller. This action
     * is divided to several smaller actions (life cycle of request).
     */
    static function dispatchRequest(){
        try{
            //extract module from request
            $dispatcherName = get_called_class();
            preg_match('/^ADS_([a-zA-Z]+)Dispatcher$/', $dispatcherName, $module);
            //load module controller
            $controllerClassName = 'ADS_' . $module[1] . 'Controller';
            if(!class_exists($controllerClassName)){
                throw new RuntimeException(sprintf('Class %s does not exist.',$controllerClassName));
            }        
            $controller = new $controllerClassName;
            if(!is_subclass_of($controller, 'ADS_DefaultController')){
                throw new RuntimeException(sprintf('Class %s is not child of DefaultController.',$controllerClassName));
            }
            //extract action from request
            $do = ADS_Input::getVar('do', 'defaultAction');        
            $camelizedAction = ucfirst($do);
            //execute action
            $lifeCycleActions = array('handle','render');
            foreach ($lifeCycleActions as &$lifeCycleAction) {
                if(method_exists($controller, $lifeCycleAction . $camelizedAction) || $lifeCycleAction == 'render'){
                    call_user_func(array($controller,$lifeCycleAction . $camelizedAction));
                }
            }
        }catch(Exception $e){
            ADS_Debug::dump($e);
        }
    }
}